package rivta.labs.schematronvalidation
import org.junit.Before
import org.junit.Test
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.NodeList

import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.*
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource

import static org.junit.Assert.assertNotNull

class ReplaceXmlTest {

    def transformerFactory
    DocumentBuilderFactory documentBuilderFactory

    @Before
    void setup() {
        transformerFactory = TransformerFactory.newInstance()

        documentBuilderFactory = DocumentBuilderFactory.newInstance()
        documentBuilderFactory.namespaceAware = true

        transformerFactory.setURIResolver(new URIResolver() {
            @Override
            Source resolve(String href, String base) throws TransformerException {
                source("/xslt/" + href)
            }
        })
    }

    @Test
    void testReplace() {

        DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder()

        Document document = builder.parse(this.getClass().getResourceAsStream('/xml/soapui-project.xml'))

        NodeList endpoints =  document.getElementsByTagNameNS('http://eviware.com/soapui/config', 'endpoint')

        for (int i = 0; i < endpoints.length; i++) {
            Element endpoint = endpoints.item(i)
            println endpoint.toString()
            endpoint.setTextContent('abc123')
            println endpoint.toString()
        }

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "{http://eviware.com/soapui/config}content {http://eviware.com/soapui/config}request")
        Source source = new DOMSource(document);
        def file = new File("merged.xml")
        println file.absolutePath
        Result output = new StreamResult(file);
        transformer.transform(source, output);
    }

    Source source(path) {
        def resource = this.getClass().getResourceAsStream(path)
        assertNotNull("resource is null", resource)
        new StreamSource(resource)
    }

    Source stringSource(contents) {
        new StreamSource(new StringReader(contents))
    }

    class StringResult extends StreamResult {
        StringWriter writer

        StringResult() {
            super()
            writer = new StringWriter()
            setWriter(writer)
        }

        @Override
        String toString() {
            writer.toString()
        }
    }


}
